﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using NetWing.Model;//系统所有的model 都在这个命名空间里，这个还是比较有好处的。
using NetWing.BPM.Core;
using NetWing.Common;
using Omu.ValueInjecter;
using NetWing.Common.Data;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Data.SqlServer;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using NetWing.Common.Other;//身份证类
using NetWing.BPM.Core.Bll;
using NetWing.BPM.Core.Model;
using NetWing.BPM.Core.Dal;

namespace NetWing.BPM.Admin.mjorderdetail.ashx
{
    /// <summary>
    /// MJOrderMainEdit 的摘要说明
    /// </summary>
    public class MJOrderMainEdit : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string jsonError = "";
            if (SysVisitor.Instance.Departments == "0")//说明没有数据权限
            {
                jsonError = new JsonMessage { Success = false, Data = "-99", Message = "登录已过期，请重新登录" }.ToString();

                context.Response.End();
            }
            //收款账号处理







            //context.Response.Write("Hello World");
            var main = HttpContext.Current.Request["main"];//得到主表json数据
            var detail = HttpContext.Current.Request["detail"];//得到明细表json数据
                                                               //得到的json数据
                                                               //[{"KeyId":"0","MJOrderid":"0","serviceName":"房租","serviceId":"3","sprice":"1500","num":"1","allprice":"1500","add_time":"2017-07-14 16:10:13","exp_time":"2017-07-14 16:10:15","note":"合同期内违约按合同处理","dep":"","depid":"0"},{"KeyId":"0","MJOrderid":"0","serviceName":"租电瓶车费","sprice":"180","num":"20","allprice":"3600","add_time":"2017-07-14 16:10:46","exp_time":"2017-07-14 16:10:53","note":"180元/月","dep":"","depid":"0","serviceId":"14"}]

            int iszf = 0;//是否包含租房合同
            //"serviceId":"3" 表明包含房租 说明有租房需要打印租房合同
            if (detail.IndexOf("\"serviceId\":3") > -1 || detail.IndexOf("\"serviceId\":\"3\"") > -1)
            {
                iszf = 1;
                //包含指定的字符串，执行相应的代码
            }

            int iszc = 0;//是否包含租车
            //"serviceId": "14"表明包含租车
            if (detail.IndexOf("\"serviceId\":14") > -1 || detail.IndexOf("\"serviceId\":\"14\"") > -1)
            {
                iszc = 1;
                //包含指定的字符串，执行相应的代码
            }


            int mainInsertedId = 0;//（主表公用）主表插入的ID
            int fmainInsertedId = 0;//财务主表插入的ID
            //加载子表公共信息
            string users = "";//客户名称
            int usersid = 0;//客户ID
            string contact = "";//经手人
            int contactid = 0;//经手人ID
            string roomno = "";//房间号
            int roomid = 0;//房间ID
            //修改时，这两个参数直接给出
            string edNumber = context.Request["edNumber"]; ;//系统订单
            string MJOrderid = context.Request["MJOrderid"];
            string account = "";//
            int accountid = 0;//
            string dep = "";//部门
            decimal total = 0;//合计金额
            decimal payment = 0;//支付总额




            #region 收款账号处理
            //account 作为总量  accountb accountc accountd 作为子项
            int c = 1;//收款方式有几种
            string accountb = "";
            string accountidb = "0";
            string shifub = "0";

            string accountc = "";
            string accountidc = "0";
            string shifuc = "0";

            string accountd = "";
            string accountidd = "0";
            string shifud = "0";

            string accounts = context.Request["account"];//收款账号
            string accountids = context.Request["accountid"];//收款账号ID
            string shifus = context.Request["shifu"];//实付
            string[] accountarr = null;
            string[] accountidarr = null;
            string[] shifuarr = null;
            if (!string.IsNullOrEmpty(accounts))//不为空
            {
                if (accounts.IndexOf(",") > -1)//包含，说明有多个
                {
                    accountarr = accounts.Split(',');
                    accountidarr = accountids.Split(',');
                    shifuarr = shifus.Split(',');
                    c = accountidarr.Length;//计算有几个从0开始
                    switch (c)
                    {
                        case 2://2个

                            accountb = accountarr[0];
                            accountidb = accountidarr[0];
                            shifub = shifuarr[0];
                            accountc = accountarr[1];
                            accountidc = accountidarr[1];
                            shifuc = shifuarr[1];

                            account = accounts;//收款账号为多账户
                            accountid = 0;//如果多账号为0
                            payment = decimal.Parse(shifub) + decimal.Parse(shifuc);//实付金额为两个账号加起来
                            break;
                        case 3://3个
                            accountb = accountarr[0];
                            accountidb = accountidarr[0];
                            shifub = shifuarr[0];
                            accountc = accountarr[1];
                            accountidc = accountidarr[1];
                            shifuc = shifuarr[1];
                            accountd = accountarr[2];
                            accountidd = accountidarr[2];
                            shifud = shifuarr[2];

                            account = accounts;//收款账号为多账户
                            accountid = 0;//如果多账号为0
                            payment = decimal.Parse(shifub) + decimal.Parse(shifuc) + decimal.Parse(shifud);//实付金额为几个账号加起来
                            break;
                        default:
                            break;
                    }

                }
                else//说明只有一个
                {
                    account = accounts;
                    accountid = int.Parse(accountids);
                    payment = decimal.Parse(shifus);
                    //如果是一个的情况 给第一个accountb的相关值
                    accountb = account;
                    accountidb = accountid.ToString();
                    shifub = payment.ToString();


                }

            }
            #endregion



            //这里可以执行一些逻辑
            //实收金额可以为0 有时候开给客户用
            //if (payment == 0)
            //{
            //    jsonError = "{\"status\":0,\"msg\":\"失败！实收金额不能为0！\"}";
            //    context.Response.Write(jsonError);
            //    context.Response.End();
            //}



            if (string.IsNullOrEmpty(main) || string.IsNullOrEmpty(detail))
            {
                jsonError = "{\"status\":0,\"msg\":\"失败！主表或子表信息为空！\"}";
                context.Response.Write(jsonError);
                context.Response.End();//输出结束
            }









            #region 数据库事务
            SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
            try
            {
                //得到最原始财务信息主表
                MJFinanceMainModel fmainTemp = new MJFinanceMainModel();
                DataTable fmainDT = SqlEasy.ExecuteDataTable("select * from MJFinanceMain where edNumber='" + edNumber + "'");
                string fmainTempJson = JSONhelper.ToJson(fmainDT);
                var fmainTempObj = JSONhelper.ConvertToObject<MJFinanceMainModel>(fmainTempJson.Replace("[", "").Replace("]", ""));//根据模型把json数据转化为obj
                //得到最原始财务信息主表


                #region 用户ID处理，如果已经是老客户从系统里获取ID，如果是新客户插入后得到新ID
                string tempUserNames = context.Request["usernames"];//入住人
                string tempUserIdCards = context.Request["useridcards"];//入住人身份号
                string tempUserMobiles = context.Request["usermobiles"];//入住人手机
                string firstUserName = "";//第一个入住人姓名
                string firstUserID = "";//第一个入住人ID号
                string firstUserIDCard = "";//第一个入住人身份证
                string firstUserMobile = "";//第一个入住人手机
                if (tempUserNames.IndexOf(",") > -1)//大于-1说明有多个入住人
                {
                    string[] firstUserNameArr = tempUserNames.Split(',');
                    firstUserName = firstUserNameArr[0];
                    string[] firstUserIDCardArr = tempUserIdCards.Split(',');
                    firstUserIDCard = firstUserIDCardArr[0];
                    string[] firstUserMobileArr = tempUserMobiles.Split(',');
                    firstUserMobile = firstUserMobileArr[0];
                }
                else//说明只有一个入住人
                {
                    firstUserName = tempUserNames;
                    firstUserIDCard = tempUserIdCards;
                    firstUserMobile = tempUserMobiles;
                }
                //检查数据库里有没有这个人
                DataRow checkUserDr = SqlEasy.ExecuteDataRow("select top 1 * from MJUser where cardid='" + firstUserIDCard + "'");
                if (checkUserDr == null)//说明没有
                {
                    string sql = "insert into MJUser (fullname,cardtype,cardid,tel,sex,birthday,depid,ownner)";
                    sql = sql + "  values ";
                    sql = sql + "('" + firstUserName + "','身份证','" + firstUserIDCard + "','" + firstUserMobile + "','" + IDCard.GetSexFromIdCard(firstUserIDCard) + "','" + IDCard.GetBrithdayFromIdCard(firstUserIDCard) + "'," + SysVisitor.Instance.cookiesUserDepId + "," + SysVisitor.Instance.cookiesUserId + ")";
                    firstUserID = DbUtils.tranInsert(sql, tran).ToString();
                }
                else//说明有
                {
                    firstUserID = checkUserDr["KeyId"].ToString();
                    //事务方法更新手机号
                    string sql = "update MJUser set tel='" + firstUserMobile + "'  where cardid='" + firstUserIDCard + "'";
                    DbUtils.tranUpdate(sql, tran);
                }






                #endregion
                #region 主表处理
                var mainobj = JSONhelper.ConvertToObject<MJOrderModel>(main);//根据模型把json数据转化为obj
                MJOrderModel mainModel = new MJOrderModel();//初始化主表模型
                mainModel.InjectFrom(mainobj);//把obj插入模型
                mainModel.KeyId = int.Parse(MJOrderid);
                mainModel.users = firstUserName;
                mainModel.usersid = int.Parse(firstUserID);
                mainModel.mobile = firstUserMobile;
                mainModel.add_time = DateTime.Now;//给主表添加时间和更新时间赋值，其他字段赋值以此类推
                mainModel.up_time = DateTime.Now;
                mainModel.userids = usersid.ToString();
                mainModel.usernames = context.Request["usernames"];//入住人
                mainModel.useridcards = context.Request["useridcards"];//入住人身份号
                mainModel.usermobiles = context.Request["usermobiles"];//入住人手机
                mainModel.paytype = context.Request["paytype"];//支付方式
                mainModel.nextpaydate = DateTime.Parse(context.Request["nextpay"]);//下次支付时间
                mainModel.shifu = payment;//实付金额
                mainModel.account = account;
                mainModel.accountid = accountid;
                mainModel.accountb = accountb;
                mainModel.accountidb = int.Parse(accountidb);
                mainModel.shifub = decimal.Parse(shifub);
                mainModel.accountc = accountc;
                mainModel.accountidc = int.Parse(accountidc);
                mainModel.shifuc = decimal.Parse(shifuc);

                mainModel.accountd = accountd;
                mainModel.accountidd = int.Parse(accountidd);
                mainModel.shifud = decimal.Parse(shifud);
                //RZ代表入住
                //mainModel.edNumber = common.mjcommon.getedNumber("RZ");//得到此次财务订单号，原来是浏览器给，现在从系统获取
                mainModel.edNumber = edNumber;//修改时，这个订单号直接从浏览器获取
                mainModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                mainModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据所有部门ID
                mainModel.printsj = 1;//入住收据，这里还需要一些判断
                                      //是否租房判断
                if (iszf == 1)
                {
                    mainModel.printwxts = 1;//温馨提示
                    mainModel.printyzsc = 1;//业主手册
                    mainModel.printzfht = 1;//租房合同
                }
                else
                {
                    mainModel.printwxts = 0;//温馨提示
                    mainModel.printyzsc = 0;//业主手册
                    mainModel.printzfht = 0;//租房合同
                }
                //是否租车判断
                if (iszc == 1)
                {
                    mainModel.printzcht = 1;//租车合同
                }
                else
                {
                    mainModel.printzcht = 0;//租车合同
                }

                //给子表需要的变量赋值
                contact = mainModel.contact;
                contactid = mainModel.contactid;
                users = mainModel.users;
                usersid = mainModel.usersid;
                roomid = mainModel.roomid;
                roomno = mainModel.roomno;
                edNumber = mainModel.edNumber;
                dep = mainModel.dep;
                total = mainModel.total;



                #region 必要参数判断
                //如果用户id、用户姓名、身份证号、手机号、房间ID、房间号为空则退出
                if (string.IsNullOrEmpty(firstUserID) || string.IsNullOrEmpty(firstUserIDCard) || string.IsNullOrEmpty(firstUserMobile) || string.IsNullOrEmpty(firstUserName) || string.IsNullOrEmpty(roomno) || string.IsNullOrEmpty(roomid.ToString()))
                {

                    jsonError = "{\"status\":0,\"msg\":\"错误！用户信息或房间信息有误！\"}";
                    context.Response.End();
                }
                #endregion


                //入住率计算需要的变量
                DateTime yearstartday = DateTime.Now;//年度开始日期
                decimal rzl = 0; //入住率
                int htts = 0;//合同入住天数
                int sjts = 0;//实际入住天数
                int yeardaysnow = 0;// 截止当日本年天数
                int yeardayscha = 0;// 全年入住天数差

                //计算本次合同入住天数
                htts = (mainModel.orderend_time - mainModel.orderstart_time).Days;


                string rzlsql = "select top 1 * from MJOrder where roomid=" + roomid + " order by KeyId desc";//从最早的一条取值
                SqlDataReader rzldr = SqlEasy.ExecuteDataReader(rzlsql);
                if (rzldr.Read())//标识有，从最老的该间房签订合同开始
                {
                    yearstartday = DateTime.Parse(rzldr["yearstartday"].ToString());//年度开始日期（这个日期会不断往下加，另外考虑如果另外一个年度。则初始化这个日期）
                    sjts = htts + int.Parse(rzldr["sjts"].ToString());//实际=本次合同天数+上次实际天数
                    yeardaysnow = (mainModel.orderend_time - yearstartday).Days;//截止当日本年天数=订单截止时间-年度开始时间
                    yeardayscha = sjts - yeardaysnow;//全年入住天数差=实际入住天数-截止当日本年天数


                }
                else//如果没有，取这次签订合同的时间
                {
                    yearstartday = mainModel.orderstart_time;//年度开始日期
                    sjts = htts;//实际天数=合同天数
                    yeardaysnow = htts;//截止当日本年天数
                    yeardayscha = sjts - yeardaysnow;//全年入住天数差


                }
                rzl = decimal.Round((decimal)sjts / yeardaysnow, 5) * 100;//计算入住率，保留小数点5位
                rzldr.Close();
                //入住率计算需要的变量
                //更新mjorder主表入住率
                mainModel.rzl = rzl;//入住率
                mainModel.htts = htts;//合同天数
                mainModel.sjts = sjts;//实际入住天数
                mainModel.yeardaysnow = yeardaysnow;//截止当日本年天数
                mainModel.yeardayscha = yeardayscha;//全年入住天数差
                mainModel.yearstartday = yearstartday;//年度开始日期（这个日期会不断往下加，另外考虑如果另外一个年度。则初始化这个日期）
                                                      //下面吧最新入住率更新到房间表


                //财务主表处理 方便以后财务统计s
                MJFinanceMainModel fmainModel = new MJFinanceMainModel();//初始化财务主表
                fmainModel.account = account;//账号
                fmainModel.accountid = accountid;//账号ID
                                                 //多收款账号处理
                fmainModel.accountb = mainModel.accountb;
                fmainModel.accountidb = mainModel.accountidb;
                fmainModel.shifub = mainModel.shifub;
                fmainModel.accountc = mainModel.accountc;
                fmainModel.accountidc = mainModel.accountidc;
                fmainModel.shifuc = mainModel.shifuc;
                fmainModel.accountd = mainModel.accountd;
                fmainModel.accountidd = mainModel.accountidd;
                fmainModel.shifud = mainModel.shifud;
                //多收款账号处理end



                fmainModel.add_time = DateTime.Now;
                fmainModel.contact = contact;
                fmainModel.contactid = contactid;
                fmainModel.dep = dep;//部门
                fmainModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                fmainModel.edNumber = edNumber;
                fmainModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                fmainModel.unit = users;//用户
                fmainModel.unitid = usersid;//用户ID
                fmainModel.note = users + "入住收据";
                fmainModel.payment = payment;
                fmainModel.total = total;
                fmainModel.operateid = SysVisitor.Instance.UserId;
                fmainModel.operate = SysVisitor.Instance.UserName;
                fmainModel.paytype = mainModel.paytype;//支付方式
                fmainModel.roomid = mainModel.roomid;
                fmainModel.roomno = mainModel.roomno;
                fmainModel.nextpaydate = mainModel.nextpaydate;//下次支付时间

                //财务主表处理 方便以后财务统计e
                #endregion
                #region 子表明细表处理
                JArray detailArr = JArray.Parse(detail);//把明细表转化为数组
                var k = detailArr[0].ToString();
                #endregion
                //mainInsertedId = DbUtils.tranInsert(mainModel, tran);//往主表插入一条
                mainInsertedId = int.Parse(MJOrderid);//修改时直接获得ID
                                                      //修改订单主表
                                                      //fmainInsertedId = DbUtils.tranInsert(fmainModel, tran);//财务主表插入一条 并提交事务

                string[] myIgnoreFields = new string[] { "keyid", "depid", "ownner" };//keyid,depid,ownner不更新 忽略
                                                                                      //JObject jsonObj = JObject.Parse(main);//获得整个json
                                                                                      //string jsonEntity = jsonObj["jsonEntity"].ToString();//取得要更新的json
                                                                                      //得到要更新的字段
                                                                                      //string[] UpdateFields = NetWing.Common.JSONhelper.ConvertJsonStrToStringArr(main);
                                                                                      //重要的更新方法，更新时只更新model模型下需要更新的字段，其他字段不更新
                //更新时只更新以下字段这样更科学
                string[] UpdateFields = { "users", "total", "usersid", "mobile", "add_time", "up_time", "userids", "usernames", "useridcards", "usermobiles", "paytype", "nextpaydate", "shifu", "account", "accountid", "accountb", "accountidb", "shifub", "accountc", "accountidc", "shifuc", "accountd", "accountidd", "shifud", "printsj", "printwxts", "printyzsc", "printzfht", "printzcht" };

                //DbUtils.tranUpdate(mainModel, tran, myIgnoreFields);
                DbUtils.tranUpdateOnlyUpdateFields(mainModel, tran, UpdateFields);


                //修改时得到财务ID
                DataRow cwdr = SqlEasy.ExecuteDataRow("select top 1 * from MJFinanceDetail where edNumber='" + edNumber + "'");
                fmainInsertedId = int.Parse(cwdr["financeId"].ToString());
                //更新财务主表
                fmainModel.KeyId = fmainInsertedId;


                DbUtils.tranUpdate(fmainModel, tran, myIgnoreFields);



                //循环明细表
                for (int i = 0; i < detailArr.Count; i++)//有几条就执行几次
                {
                    //先循环插入订单明细表s
                    var detailobj = JSONhelper.ConvertToObject<MJOrderDetailModel>(detailArr[i].ToString());//根据模型把明细表转化为obj
                    MJOrderDetailModel detailModel = new MJOrderDetailModel();//初始化明细表模型
                    detailModel.InjectFrom(detailobj);//把obj插入模型
                    detailModel.MJOrderid = mainInsertedId;//父子表关联  养成一个习惯两表关联 字表里有 主表名+id 即主表id
                    //detailModel.add_time = DateTime.Now;
                    detailModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                    detailModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据所有部门ID
                    //给字表信息赋值
                    //detailModel.users = users;
                    //detailModel.usersid = usersid;
                    detailModel.users = mainModel.users;
                    detailModel.usersid = mainModel.usersid;
                    detailModel.roomno = roomno;
                    detailModel.roomid = roomid;
                    detailModel.contact = contact;
                    detailModel.contactid = contactid;
                    detailModel.edNumber = edNumber;
                    detailModel.paytype = mainModel.paytype;//支付方式
                    detailModel.nextpaydate = mainModel.nextpaydate;//下次支付时间
                                                                    //detailModel.up_time = DateTime.Now; 每个都应该有up_time 和add_time
                                                                    //DbUtils.tranInsert(detailModel, tran);//执行写入明细表

                    string[] detIgnoreFields = new string[] { "keyid", "depid", "ownner" };
                    DbUtils.tranUpdate(detailModel, tran, detIgnoreFields);
                    //先循环插入订单明细表e

                    if (detailModel.serviceId == 3)//房租
                    {
                        //更新房间表  只执行一次
                        MJRoomsModel roomModel = new MJRoomsModel();
                        roomModel.KeyId = mainModel.roomid;//房间keyId
                        roomModel.zuqi = mainModel.zuqi;
                        roomModel.jzrs = mainModel.jzrs;
                        roomModel.userids = (mainModel.usersid).ToString();//更新租赁用户id
                        roomModel.usermobiles = mainModel.usermobiles;
                        roomModel.usernames = mainModel.usernames;
                        roomModel.useridcards = mainModel.useridcards;
                        roomModel.paytype = mainModel.paytype;//支付方式
                        roomModel.nextpaydate = mainModel.nextpaydate;//下次付房租时间
                        roomModel.state = "租赁中";
                        roomModel.add_time = detailModel.add_time;
                        roomModel.up_time = detailModel.add_time;
                        roomModel.price = detailModel.sprice;//更新价格用于计算平均租金
                        roomModel.exp_time = detailModel.exp_time;//到期时间
                        roomModel.orderstart_time = mainModel.orderstart_time;//合同开始时间
                        roomModel.orderend_time = mainModel.orderend_time;//合同结束时间
                        roomModel.OrderId = mainInsertedId;//把mjorder的id插进去，方便识别
                        roomModel.rzl = rzl;//更新最新入住率
                        string[] IgnoreFields = { "keyid", "vest", "vestid", "roomnumber", "roomtype", "remarks", "depid", "ownner", "oprice", "quarterprice", "halfyearprice", "yearprice" };//不更新的字段
                        DbUtils.tranUpdate(roomModel, tran, IgnoreFields);//事务方法更新表
                        //更新房间表 只执行一次
                    }




                    //循环插入财务明细表s
                    MJFinanceDetailModel fdetailModel = new MJFinanceDetailModel();//初始化明细表模型
                    fdetailModel.financeId = fmainInsertedId;//财务主表ID
                    fdetailModel.ftype = "";
                    fdetailModel.edNumber = edNumber;
                    fdetailModel.subject = detailModel.serviceName;
                    fdetailModel.subjectid = detailModel.serviceId;
                    fdetailModel.num = detailModel.num;
                    fdetailModel.sprice = detailModel.sprice;
                    fdetailModel.sumMoney = detailModel.allprice;
                    fdetailModel.dep = dep;
                    fdetailModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);
                    fdetailModel.note = detailModel.note;
                    fdetailModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);
                    fdetailModel.stime = detailModel.add_time;
                    fdetailModel.etime = detailModel.exp_time;
                    fdetailModel.userid = mainModel.usersid;
                    fdetailModel.username = mainModel.users;
                    fdetailModel.mobile = mainModel.mobile;
                    fdetailModel.contact = mainModel.contact;
                    fdetailModel.contactid = mainModel.contactid;
                    fdetailModel.add_time = DateTime.Now;
                    fdetailModel.up_time = DateTime.Now;
                    fdetailModel.paytype = mainModel.paytype;
                    fdetailModel.nextpaydate = mainModel.nextpaydate;//下次付房租时间
                    fdetailModel.roomid = mainModel.roomid;
                    fdetailModel.roomno = mainModel.roomno;//房间号
                    //DbUtils.tranInsert(fdetailModel, tran);//执行写入财务明细表
                    int f = 0;
                    f = DbUtils.tranUpdateWhatWhere(fdetailModel, " orderdetailid = " + detailModel.KeyId, tran, new string[] { "keyid", "depid", "orderdetailid" });
                    if (f == 0)//更新失败说明找不到对应关系
                    {
                        jsonError = "{\"status\":0,\"msg\":\"更新失败，明细表没找到对应关系\"}";
                        context.Response.End();
                    }
                    //DbUtils.tranUpdateWhatWhere<DemoRuKuDanMingXiModel>(new {rkdId = rkdid});
                    //循环插入财务明细表e




                }
                //循环明细表


                //减掉修改之前的银行账户余额
                DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance-" + fmainTempObj.shifub + " where KeyId=" + fmainTempObj.accountidb + "", tran);
                DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance-" + fmainTempObj.shifuc + " where KeyId=" + fmainTempObj.accountidc + "", tran);
                DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance-" + fmainTempObj.shifud + " where KeyId=" + fmainTempObj.accountidd + "", tran);




                //事务的方法执行sql语句
                //可以写些什么逻辑放在这里
                switch (c)
                {
                    case 2://有两个收款账户的情况
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + mainModel.shifub + " where KeyId=" + mainModel.accountidb + "", tran);
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + mainModel.shifuc + " where KeyId=" + mainModel.accountidc + "", tran);
                        break;
                    case 3:
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + mainModel.shifub + " where KeyId=" + mainModel.accountidb + "", tran);
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + mainModel.shifuc + " where KeyId=" + mainModel.accountidc + "", tran);
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + mainModel.shifud + " where KeyId=" + mainModel.accountidd + "", tran);
                        break;

                    default://有一个收款账户的情况
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + mainModel.shifu + " where KeyId=" + mainModel.accountid + "", tran);
                        break;
                }



                tran.Commit();//提交执行事务
                LogModel log = new LogModel();
                log.BusinessName = "入住收据修改成功";
                log.OperationIp = PublicMethod.GetClientIP();
                log.OperationTime = DateTime.Now;
                log.PrimaryKey = "";
                log.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                log.TableName = "";
                log.note = "服务主表id:" + mainInsertedId + "；财务主表id:" + fmainInsertedId + "";
                log.OperationType = (int)OperationType.Other;
                LogDal.Instance.Insert(log);

                context.Response.Write("{\"status\":1,\"msg\":\"办理成功，请转到业务办理处理其他业务！\"}");
            }
            #endregion
            catch (Exception e)
            {
                LogModel log = new LogModel();
                log.BusinessName = "入住收据修改失败";
                log.OperationIp = PublicMethod.GetClientIP();
                log.OperationTime = DateTime.Now;
                log.PrimaryKey = "";
                log.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                log.TableName = "";
                log.note = e.ToString();
                log.OperationType = (int)OperationType.Other;
                LogDal.Instance.Insert(log);

                tran.Rollback();//错误！事务回滚！
                if (string.IsNullOrEmpty(jsonError))
                {
                    jsonError = e.Message;
                }
                context.Response.Write(jsonError);
                context.Response.End();
                //throw;
            }




        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}